import SwiftUI
import Kingfisher

struct ComicViewPics: View {
    @ObservedObject var viewModel: ComicPicsViewModel
    @Binding var currentIndex: Int
    
    @Binding var ep_id: Int
    @Binding var hasAppeared: Bool
    @Binding var currentAll: Int
    @Binding var selectIndex: Int
    @State private var hasLoadedImages = false  // 确保仅在图片滑动时更新
    
    var body: some View {
        ScrollViewReader { proxy in
            LazyVStack(alignment: .leading, spacing: 0) {
                ForEach(viewModel.pics) { item in
                    KFImage(URL(string: item.cover)!)
                        .resizable()
                        .scaledToFit()  // 保持图片比例
                        .aspectRatio(contentMode: .fit)  // 适应父视图并保持比例
                        .frame(maxWidth: .infinity)  // 宽度百分百
                        .clipped()  // 剪切溢出的部分
                        .id(item.id)  // 使用 item.id 作为唯一标识符
                        

                        .onAppear {
                            if hasLoadedImages {
                                // 在图片出现在屏幕上时更新当前图片索引
                                if let index = viewModel.pics.firstIndex(where: { $0.id == item.id }) {
                                    // 只有在当前索引改变时更新 currentIndex
                                    if currentIndex != index {
                                        currentIndex = index
                                    }
                                }
                            }
                        }
                        .onDisappear {
                            // 释放图片内存或清理缓存
                            KingfisherManager.shared.cache.clearMemoryCache()
                        }

                        .animation(.spring(response: 0.6, dampingFraction: 0.8, blendDuration: 0.5).delay(0.1), value: currentIndex)

                }
            }
            .onChange(of: selectIndex) { oldValue, newIndex in
                print("Current Index: \(currentIndex), New Index: \(newIndex)")
                if let itemId = viewModel.pics[safe: newIndex]?.id {
                    withAnimation(.easeInOut(duration: 0.5)) { // 延长持续时间来让滚动更加平滑
                        proxy.scrollTo(itemId, anchor: .top)
                    }
                    
                }
            }
            .onChange(of: ep_id) { oldValue, newIndex in
                viewModel.get_list(ep_id: ep_id) { count in
                    // 在这里更新 currentAll
                    DispatchQueue.main.async {
                        currentAll = count
                        currentIndex = 1
                        selectIndex = 0
                    }
                }
            }
            .onAppear {
                if !hasAppeared {
                    viewModel.get_list(ep_id: ep_id) { count in
                        // 在这里更新 currentAll
                        DispatchQueue.main.async {
                            currentAll = count
                        }
                    }
                    hasAppeared = true
                }
                // 加载完成后，开始响应图片滑动
                DispatchQueue.main.async {
                    hasLoadedImages = true
                }
            }
       
        }
    }
}

// 扩展数组，提供安全访问方法
extension Collection {
    subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

#Preview {
    @Previewable @State var currentAll = 100
    @Previewable @State var selectIndex: Int = 0
    @Previewable @State var currentIndex: Int = 0
    @Previewable @State var ep_name: String = "章节名称"
    @Previewable @State var ep_id: Int = 238721
    @Previewable @State var hasAppeared = false
    @Previewable @State var viewModel = ComicPicsViewModel()
    
    ComicViewPics(viewModel: viewModel, currentIndex: $currentIndex, ep_id: $ep_id, hasAppeared: $hasAppeared,currentAll: $currentAll,selectIndex: $selectIndex)
}
 
